package com.boot.hospital.score.core.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.boot.hospital.score.common.enums.ResultCodeEnum;
import com.boot.hospital.score.common.util.JwtUtil;
import com.boot.hospital.score.common.wrapper.ResponseWrapper;
import com.boot.hospital.score.core.service.UserService;
import com.boot.hospital.score.dao.entity.User;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@PropertySources(value = {
        @PropertySource(value = {"classpath:important.properties", "classpath:application.properties"}, encoding = "utf-8")
})
@EnableAutoConfiguration
public class UserController {

    @Resource
    private UserService userService;

    @ApiOperation("添加用户信息")
    @PostMapping(value = "/add")
    public ResponseWrapper<Object> addUser(@RequestParam Map<String, String> params) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {

            String password = params.get("password");

            User user = new User();
            user.setUserName(params.get("username"));
            user.setUserType(params.get("userType"));
            user.setMemo(params.get("memo"));
            user.setPassword(password);
            user.setDept(params.get("dept"));

            if (user.getUserType().equals("")) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("用户类别为空");
                return responseWrapper;
            }
            if (user.getPassword().equals("")) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("密码为空");
                return responseWrapper;
            }
            if (user.getUserName().equals("")) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("用户名称为空");
                return responseWrapper;
            }
            if (userService.getUserByUserName(user.getUserName()) != null) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("用户名称已存在");
                return responseWrapper;
            }
            if (user.getUserType().equals("admin")) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg("admin类型不可注册");
                return responseWrapper;
            }

            user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

            int result = userService.insert(user);

            if (result > 0) {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
            } else {
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                responseWrapper.setMsg(ResultCodeEnum.ADD_FAIL.getName());
            }
        } catch (Exception e) {
            log.error("用户添加失败：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }
    @ApiOperation("检验秘钥")
    @GetMapping(value = "/testToken")
    public ResponseWrapper<Object> testToken(HttpServletRequest request) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {
            // 处理自己的逻辑业务
            // 此时我们想要获取 token中的用户信息，token经过拦截器拦截绝对是正确的
            String token = request.getHeader("token");

            DecodedJWT tokenInfo = JwtUtil.getTokenInfo(token);

            User user = new User();
            user.setUserName(tokenInfo.getClaim("username").asString());
            user.setUserId(tokenInfo.getClaim("userId").asString());
            user.setUserType(tokenInfo.getClaim("userType").asString());

            // 返回用户的相关信息的map集合
            responseWrapper.setData(user);
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
            responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
        } catch (Exception e) {
            log.error("检验秘钥：{}", ExceptionUtils.getStackTrace(e));
            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }

        return responseWrapper;
    }

//    @ApiOperation("查询所有用户信息")
//    @GetMapping(value = "/selectAll")
//    public ResponseWrapper<Object> selectAll() {
//        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
//        List<User> userList = userService.selectAll();
//        responseWrapper.setData(userList);
//        return responseWrapper;
//    }


    @ApiOperation("管理登录")
    @PostMapping("/login")
    public ResponseWrapper<Object> userLogin(@RequestParam Map<String, String> params) {
        ResponseWrapper<Object> responseWrapper = new ResponseWrapper<>();
        try {

            User lawUser = userService.getUserByUserName(params.get("username"));

            if (lawUser != null) {

                String password = lawUser.getPassword();

                String loginPassword = params.get("password");
                loginPassword = DigestUtils.md5DigestAsHex(loginPassword.getBytes());

                if (password.equals(loginPassword)) {
                    //密码正确
                    Map<String, String> info = new HashMap<>();
                    info.put("username", params.get("username"));
                    info.put("userId",lawUser.getUserId());
                    info.put("userType",lawUser.getUserType());

                    String token = JwtUtil.createToken(info);

                    HashMap<String, Object> loginInfo = new HashMap<>();

                    loginInfo.put("token", token);

                    responseWrapper.setCode(String.valueOf(ResultCodeEnum.SUCCESS.getCode()));
                    responseWrapper.setMsg(ResultCodeEnum.SUCCESS.getName());
                    responseWrapper.setData(loginInfo);

                } else {
                    log.error("账号密码错误");
                    responseWrapper.setMsg(ResultCodeEnum.PASSWORD_ERROR.getName());
                    responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
                }
            } else {
                log.error("用户名不存在");
                responseWrapper.setMsg(ResultCodeEnum.LOGINNAME_NOT_EXIT_ERROR.getName());
                responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
            }
        } catch (Exception e) {
            log.error("用户登陆失败：{}", ExceptionUtils.getStackTrace(e));

            responseWrapper.setMsg(ExceptionUtils.getStackTrace(e));
            responseWrapper.setCode(String.valueOf(ResultCodeEnum.FAIL.getCode()));
        }
        return responseWrapper;
    }


}